package com.annotation.demo;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test {
    public static void main(String[] args) throws IOException {
        //获取对象
        Calculator calculator = new Calculator();
        //获取字节码对象
        Class aClass = calculator.getClass();
        //获取所有方法
        Method[] methods = aClass.getMethods();
        int num = 0;//出现异常的次数
        BufferedWriter bw = new BufferedWriter(new FileWriter("bug.txt"));
        for (Method method : methods) {
            //判断方法上是否有check注解
            if (method.isAnnotationPresent(Check.class)) {
                //有注解就执行
                try {
                    method.invoke(calculator);
                } catch (Exception e) {
                    //捕获异常
                    //记录到文件中
                    num++;
                    bw.write(method.getName() + "方法出现异常");
                    bw.newLine();
                    bw.write("异常的名称" + e.getCause().getClass().getSimpleName());
                    bw.newLine();
                    bw.write("异常的原因" + e.getCause().getMessage());
                    bw.newLine();
                }
            }
        }

        bw.write("本次测试一共出现" + num +"次异常");
        bw.flush();
        bw.close();


        //捕获异常
        //
    }
}
